package com.xrj.gateway.controller;


import cn.hutool.http.HttpRequest;
import com.mall.common.annotation.PassToken;
import com.mall.common.response.Response;
import com.mall.common.validate.ValidationUtils;
import com.mall.user.constant.UserServiceEnum;
import com.mall.user.dto.bo.resp.UserResp;
import com.mall.user.dto.bo.resp.VerifyCode;
import com.mall.user.dto.entity.TbMember;
import com.mall.user.dto.vo.UserVo;
import com.mall.user.service.TbMemberService;
import com.mall.user.service.VerifyCodeService;
import com.xrj.gateway.interceter.TokenInterceptor;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import utils.CookieUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xrj
 * @since 2022-04-30
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private final static String VERIFY_CODE = "kaptcha_uuid";

    @Reference(timeout = 30000, check = false)
    private TbMemberService memberService;

    @Reference(timeout = 30000, check = false)
    private VerifyCodeService verifyCodeService;


    @ApiOperation(value = "用户登录", httpMethod = "POST")
    @PostMapping("/login")
    @PassToken
    public Object login(@RequestBody UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        ValidationUtils.ValidResult validResult = ValidationUtils.validateBean(userVo);
        if (validResult.isHasErrors()) {
            return Response.checkFailed(validResult.getErrorsStr());
        }
        //判断验证码是否正确
        String uuid = CookieUtils.getCookieValue(request, VERIFY_CODE);
        VerifyCode req = new VerifyCode();
        req.setImageCode(userVo.getCaptcha());
        req.setUuid(uuid);
        VerifyCode codeResp = verifyCodeService.validateVerifyCode(req);
        if (!UserServiceEnum.SUCCESS.getCode().equals(codeResp.getCode())) {
            return Response.checkFailed("验证码输入错误!");
        }
        //比对用户口令
        UserResp userResp = memberService.login(userVo);
        if (!UserServiceEnum.SUCCESS.getCode().equals(codeResp.getCode())) {
            return Response.checkFailed(userResp.getMsg());
        }
        //设置cookie
        Cookie cookie = CookieUtils.genCookie("access_token", userResp.getLoginModel().getToken(), "/", 60 * 60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return Response.success(userResp.getLoginModel(), "登录成功");
    }

    @ApiOperation(value = "已登录用户解析token登录",httpMethod = "GET")
    @GetMapping("/login")
    public Object login(HttpServletRequest request){
        TbMember user;
        try {
            user = (TbMember) request.getAttribute(TokenInterceptor.USER_INFO_KEY);
        } catch (Exception e) {
            return Response.operationFailed("验证失败!");
        }
        if (user == null) return Response.operationFailed("验证失败!");
        return Response.success(user,"验证成功!");
    }

    @ApiOperation(value = "获取验证码", httpMethod = "GET")
    @GetMapping("/kaptcha")
    @PassToken
    public Object getVerifyCode(HttpServletResponse response) {
        VerifyCode verifyCode = verifyCodeService.getVerifyCode();
        String imageCode = verifyCode.getImageCode();
        if (StringUtils.isBlank(imageCode)) {
            return Response.operationFailed("验证码生成失败!");
        }
        //设置cookie,传入uuid,后续在redis中比对验证
        Cookie cookie = CookieUtils.genCookie(VERIFY_CODE, verifyCode.getUuid(), "/", 60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return Response.success(imageCode, "验证码生成成功!");
    }

    @ApiOperation(value = "校验验证码", httpMethod = "POST")
    @PostMapping("/kaptcha")
    @PassToken
    public Object verifyCode(String code, HttpServletRequest request) {
        String uuid = CookieUtils.getCookieValue(request, VERIFY_CODE);
        if (StringUtils.isBlank(code) || StringUtils.isBlank(uuid)) {
            return Response.checkFailed("参数非法!");
        }
        VerifyCode verifyCode = new VerifyCode();
        verifyCode.setImageCode(code);
        verifyCode.setUuid(uuid);
        VerifyCode resp = verifyCodeService.validateVerifyCode(verifyCode);
        if (!UserServiceEnum.SUCCESS.getCode().equals(resp.getCode())) {
            return Response.checkFailed("验证码输入错误!");
        }
        return Response.success("验证码验证成功!");
    }

}
